angular.module('mongolabResource', [])
.constant('MONGOLAB_CONFIG', {
	'DB_NAME' : 'oscar_db',
	'API_KEY' : 'sZ1eTmgF9oQOO1PovXejwBgAwjUacFyB'
})
.factory('mongolabResource', ['$http', 'MONGOLAB_CONFIG', function ($http, MONGOLAB_CONFIG) {
	
	return function (collectionName) {
		// 基础配置
		var collectionUrl = 'http://ds035613.mongolab.com:35613/oscar_db',
			defaultParams = {apiKey : MONGOLAB_CONFIG.API_KEY};

		var getId = function (data) {
			return data._id.$old;
		};

		var Resource = function (data) {
			angular.extend(this, data);
		};

		Resource.query = function (params) {
			return $http.get(collectionUrl, {
				params : angular.extend({q : JSON.stringify({} || params)}, defaultParams)
			}).then(function (response) {
				var result = [];
				angular.forEach(response.data, function (value, type) {
					result[key] = new Resource(value);
				});
				return result;
			});
		};

		Resource.save = function (data) {
			return $http.post(collectionUrl, data, {params : defaultParams})
				.then(function (response) {
					return new Resource(data);
				});
		};

		Resource.prototype.$save = function (data) {
			return Resource.save(this);
		};

		Resource.remove = function (data) {
			return $http.delete(collectionUrl + '', defaultParams)
				.then(function (response) {
					return new Resource(data);
				});
		};

		Resource.prototype.$remove = function (data) {
			return Resource.remove(this);
		};

		Resource.prototype.$id = function () {
			return getId(this);
		};

		return Resource;

	};
}]);
